<template>
  <div class="year-detail">
    <div class="tempContainer">
      <el-card>
        当前计划:{{oneYearData.planTime}}-{{oneYearData.draftName}}-{{oneYearData.version}}
        <el-button type="primary" size="mini" style="float:right;margin-top:-10px" @click="mineBack">返回</el-button>
        <el-button type="primary" size="mini" style="float:right;margin-top:-10px;margin-right:10px" @click="toDetailPlan(oneYearData.draftId)">详情</el-button>
        <el-button type="primary" size="mini" style="float:right;margin-top:-10px" @click="toUpdatePlan(mineYearSet,oneYearData.draftId)">调整年计划</el-button>
        <circle-compent :detailCatagrayCount="(oneYearData.yearPlanAmount/10000).toFixed(2)" :detailProductCount="oneYearData.yearFinishRatio"
                        :detailOffLine="oneYearData.categoryNumber" :percent="oneYearData.productCodeNumber" :titleName="titleName"></circle-compent>
      </el-card>
      <div style="margin-top: 25px">
        <el-select v-model="valueSetYear" @change="changeYearSer" size="mini" placeholder="请选择">
          <el-option v-for="(item,index) in 10" :key="index"
                     :label="`${currentYear-item+1}年`" :value="(currentYear-item+1)">
          </el-option>
        </el-select>
      </div>
      <div id="saleSummaryChart" style="height: 300px;width:100%;margin:10px"></div>
      <el-radio-group  size="small" v-model="plan" @change="planSelect">
        <el-radio-button label="0">计划草案</el-radio-button>
        <el-radio-button label="1">历史计划</el-radio-button>
      </el-radio-group>
      <span v-if="plan == '0'">创建时间</span>
      <span v-else>发布时间</span>
      <el-date-picker style="width: 300px" size="small" v-model="dataPicker"
                     @change="planSelect" type="daterange"
                     value-format="yyyy-MM-dd" range-separator="至"
                     start-placeholder="开始日期" end-placeholder="结束日期">
     </el-date-picker>
      <el-table :data="twoPageTable" style="width: 100%;margin-top:20px">
        <el-table-column
          v-if="plan == '0'"
          label="计划草案表"
          key="2">
          <template slot-scope="scope">{{scope.row.draftName}}-{{scope.row.version}}</template>
        </el-table-column>
        <el-table-column
          key="1"
          v-if="plan == '1'"
          label="历史计划表">
          <template slot-scope="scope">{{scope.row.draftName}}-{{scope.row.version}}</template>
        </el-table-column>
        <el-table-column
          prop="yearPlanAmount"
          :formatter="formatterColumn"
          :sort-method="sortYearPlanAmount"
          sortable
          label="计划销额(万元)">
        </el-table-column>
        <el-table-column
          prop="yearFinishRatio"
          label="完成度"
          :sort-method="sortYearFinishRatio"
          sortable>
        </el-table-column>
        <el-table-column
          prop="categoryNumber"
          sortable
          label="品类数(个)">
        </el-table-column>
        <el-table-column
          prop="productCodeNumber"
          sortable
          label="产品数(个)">
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          v-if="plan == '0'"
          key="3"
          sortable>
        </el-table-column>
        <el-table-column
            prop="createTime"
            label="发布时间"
            v-if="plan == '1'"
            key="4"
            sortable>
        </el-table-column>
        <el-table-column
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" v-if="plan == '0'" @click="deleteDraftByDraftId(scope.row.draftId)">删除</el-button>
            <el-button type="text" v-if="plan == '0'" @click="draftToEdit(scope.row.planTime,scope.row.draftId)">详情/发布</el-button>
            <el-button type="text" v-else @click="toDetailPlan(scope.row.draftId)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
  import * as opreate from 'api/getData'
  import CircleCompent from 'router/marketSale/compentSet/circleCompent'
  let currentYear = new Date().getFullYear()

  export default {
    name: "year-detail",
    data(){
      return{
        pickerOptions:{
          disabledDate: this.limitSet
        },
        plan:'0',
        dataPicker:'',
        valueSetYear:'',
        currentYear:currentYear,
        oneYearData:'',
        twoPageTable:[],
        mainchart: [],
        titleName:[
          '年计划销额（万元）',
          '年销额完成度',
          undefined,
          '品类数（个）',
          '产品数（个）'
        ],
        mineYearSet: ''
      }
    },
    components:{
      CircleCompent
    },
    mounted(){
      this.mineYearSet = this.$route.params.mineYear
      this.valueSetYear = `${this.mineYearSet}年`
      this.currentYear = currentYear <= this.mineYearSet ? this.mineYearSet : currentYear
      this.getDetailPlan(this.mineYearSet)
      this.getdrafts(this.mineYearSet)
    },
    methods:{
      formatterColumn(row, column){
        return ((row.yearPlanAmount || 0)/10000).toFixed(2)
      },
      sortYearFinishRatio(prev,next){
        return prev.yearFinishRatio.slice(0,-1) - next.yearFinishRatio.slice(0,-1)
      },
      sortYearPlanAmount(prev,next){
        return parseFloat(prev.yearPlanAmount || '0') - parseFloat(next.yearPlanAmount || '0')
      },
      limitSet: function(time) {
        return time.getTime() < new Date(this.mineYearSet,1,1).getTime() || time.getTime() > new Date(this.mineYearSet,12,31).getTime()
      },
      toUpdatePlan(mineYearSet, draftId){
        this.$router.push({
          name:'editYearPlan',
          params: { mineYear: this.mineYearSet, draftId: draftId }
        })
      },
      draftToEdit(editYear,draftId){
        this.$router.push({
          name:'editYearPlan',
          params: { mineYear: this.mineYearSet, draftId: draftId }
        })
      },
      toDetailPlan(draftId){
        this.$router.push({
          name: 'planYearDetail',
          params: { mineYear: this.mineYearSet, draftId: draftId }
        })
      },
      planSelect(){
        "1" == this.plan ? this.getHistory(this.mineYearSet) : this.getdrafts(this.mineYearSet)
      },
      mineBack(){
        this.$router.back(-1)
      },
      deleteDraftByDraftId (draftId) {
        this.$confirm('确认删除该草案？').then(state => {
          opreate.deleteDraftById({ draftId }).then(res => {
            if('200' == res.code){
              this.getdrafts(this.mineYearSet)
              this.$message.success('删除成功');
            }else {
              this.$message.success('操作失败，稍后再试');
            }
          })
        }).catch(() => {})
      },
      getDetailPlan(yearPlanTime){
        opreate.detailPlanYear({ yearPlanTime }).then(res => {
          this.oneYearData = res.data
          this.changeYearSer(yearPlanTime)
        })
      },
      getdrafts(yearPlanTime){
        let [ firstTime, lastTime ] = this.dataPicker
        opreate.getDraftAllResult({
          yearPlanTime: yearPlanTime,
          firstTime: firstTime || null,
          lastTime: lastTime || null
        }).then(res => {
          this.twoPageTable = res.data || []
        })
      },
      getHistory(yearPlanTime){
        let [ firstTime, lastTime ] = this.dataPicker
        opreate.getDraftHistoryAllResult({
          yearPlanTime: yearPlanTime,
          firstTimeDevelop: firstTime || null,
          lastTimeDevelop: lastTime || null
        }).then(res => {
          this.twoPageTable = res.data || []
        })
      },
      changeYearSer(dateTime) {
        let myChart = this.$echarts.init(document.getElementById('saleSummaryChart'));
        opreate.getSaleMonthData({ productCode: '', dateTime: dateTime }).then(res => {
          let [ mainchart = [] ] = res.data || []
          this.mainchart = mainchart || []
          let option = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'cross',
                crossStyle: {
                  color: '#999'
                }
              },
              formatter:'{b}<br />{a0}: {c0}万<br />{a1}: {c1}%<br />{a2}: {c2}万<br />{a3}: {c3}%'
            },
            legend: {
              data:['销售量','销量环比','销售额','销额环比']
            },
            xAxis: [
              {
                type: 'category',
                data: this.mainchart.map(item => item.dateTime)
              }
            ],
            yAxis: [
              {
                type: 'value',
                name: '销售量/销售额（万）',
                axisLabel: {
                  formatter: '{value} '
                }
              },
              {
                type: 'value',
                name: '环比',
                axisLabel: {
                  formatter: '{value}% '
                }
              }
            ],
            series: [
              {
                name:'销售量',
                type:'bar',
                itemStyle: {
                  color: '#9c96e7'
                },
                barMaxWidth: '25px',
                data:this.mainchart.map(item => {
                  return ((item.actualSalesCount || 0)/10000).toFixed(2)
                })
              },
              {
                name:'销量环比',
                type:'line',
                smooth: true,
                yAxisIndex: 1,
                itemStyle: {
                  color: '#9c96e7'
                },
                data:this.mainchart.map(item => item.actualSalesCountRingRatio || '0.00')
              },
              {
                name:'销售额',
                type:'bar',
                itemStyle: {
                  color: '#64bef5'
                },
                barMaxWidth: '25px',
                data:this.mainchart.map(item => {
                  return ((item.actualSalesAmount || 0)/10000).toFixed(2)
                })
              },
              {
                name:'销额环比',
                type:'line',
                smooth: true,
                yAxisIndex: 1,
                itemStyle: {
                  color: '#64bef5'
                },
                data:this.mainchart.map(item => item.actualSalesAmountRingRatio || '0.00')
              }
            ]
          };
          myChart.setOption(option); // 使用刚指定的配置项和数据显示图表
        })
      }
    }
  }
</script>

<style scoped>

</style>
